package com.blog.servlet;

import com.blog.dao.ArticleDao;
import com.blog.dao.impl.ArticleDaoImpl;
import com.blog.entity.Article;
import com.blog.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 文章列表Servlet
 */
@WebServlet({"/articles", "/index"})  // 可映射多个路径
public class ArticleListServlet extends HttpServlet {
    private ArticleDao articleDao = new ArticleDaoImpl();

    // 每页显示文章数量
    private static final int PAGE_SIZE = 5;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取当前页码，默认为1
        String pageStr = request.getParameter("page");
        int page = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
                if (page < 1) page = 1;  // 页码不能小于1
            } catch (NumberFormatException e) {
                // 页码格式错误，使用默认值1
            }
        }

        // 2. 查询文章列表和总数
        List<Article> articleList = articleDao.findByPage(page, PAGE_SIZE);
        int totalCount = articleDao.getTotalCount();

        // 3. 计算总页数
        int totalPage = (totalCount + PAGE_SIZE - 1) / PAGE_SIZE;

        // 4. 将数据存入request域
        request.setAttribute("articleList", articleList);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("totalCount", totalCount);

        // 5. 转发到文章列表页面
        request.getRequestDispatcher("/article/list.jsp").forward(request, response);
    }
}